import { defineConfig } from 'vite'
import { resolve } from 'path'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
import prismjs from 'vite-plugin-prismjs'
import Compression from 'vite-plugin-compression'
import OptimizationPersist from 'vite-plugin-optimize-persist'
import PkgConfig from 'vite-plugin-package-config'
import environment from 'vite-plugin-environment'
import { terser } from 'rollup-plugin-terser'
import htmlEnv from 'vite-plugin-html-env'

export default defineConfig({
  plugins: [
    vue(),
    PkgConfig(),
    OptimizationPersist(),
    htmlEnv({
      compiler: true,
    }),
    environment({
      file: '.env',
    }),
    Components({
      resolvers: [NaiveUiResolver()],
    }),
    Compression({
      filter: /.(js|mjs|json|css)$/i, // 选择哪些文件要压缩
      ext: '.gz',
      algorithm: 'gzip',
      deleteOriginFile: true,
    }),
    prismjs({
      languages: 'all',
    }),
  ],
  server: {
    host: true,
    open: false,
    port: 666,
    strictPort: true,
    hmr: {
      overlay: false,
    },
  },
  resolve: {
    alias: [
      { find: '@', replacement: resolve(__dirname, 'src') },
      { find: '@cmps', replacement: resolve(__dirname, 'src/components') },
      { find: '@api', replacement: resolve(__dirname, 'src/api') },
      { find: '@styles', replacement: resolve(__dirname, 'src/assets/styles') },
    ],
  },
  build: {
    target: 'es2015',
    outDir: 'dist',
    assetsDir: 'static',
    reportCompressedSize: false,
    cssTarget: 'chrome61',
    minify: 'terser',
    brotliSize: false,
    rollupOptions: {
      // 使用 terser 插件去除 console.log() 和注释
      plugins: [
        terser({
          format: { comments: false },
          compress: { drop_console: true, drop_debugger: true },
        }),
      ],
      output: {
        manualChunks: {
          // 拆分代码，分包，配置完后自动按需加载。
          vue: ['vue', 'vue-router'],
          axios: ['axios'],
          pinia: ['pinia'],
        },
      },
    },
  },
})
